package com.gm.wholesale.module.tenxunQcloud;

import android.content.Context;
import android.os.Looper;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.interfaces.ICallBackListener;
import com.gm.commonlib.interfaces.IResultListener;
import com.gm.commonlib.module.image.ImageUtil;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.BuildConfig;
import com.gm.wholesale.module.tenxunQcloud.bean.TenXunSdkKeyBean;
import com.gm.wholesale.module.tenxunQcloud.bean.UploadImageBean;
import com.gm.wholesale.module.tenxunQcloud.model.TenXunYunModel;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.CosXmlSimpleService;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.OnCompressListener;

public class TenxunUploadUtil {

    public synchronized static void getKey(Context context, String imagePath, IResultListener<CosXmlSimpleService> listener) {

        TenXunYunModel.getTenXunYunKey(imagePath, new BaseHttpObserver<>() {
            @Override
            protected void handleResultOkResp(DataResp<TenXunSdkKeyBean> resp) {
                listener.onResult(getCosXmlSimpleService(context, resp.getData()));
            }
        });


    }

    private static CosXmlSimpleService getCosXmlSimpleService(Context context, TenXunSdkKeyBean tenXunSdkKeyBean) {
        // keyDuration 为请求中的密钥有效期，单位为秒
        MySessionCredentialProvider mySessionCredentialProvider = new MySessionCredentialProvider(tenXunSdkKeyBean);

        // 存储桶所在地域简称，例如广州地区是 ap-guangzhou
        String region = TenXunConstans.REGION;

        // 创建 CosXmlServiceConfig 对象，根据需要修改默认的配置参数
        CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder()
                .setRegion(region)
                .isHttps(true) // 使用 HTTPS 请求, 默认为 HTTP 请求
                .builder();

        // 初始化 COS Service，获取实例
        CosXmlSimpleService cosXmlService = new CosXmlSimpleService(context,
                serviceConfig, mySessionCredentialProvider);
        return cosXmlService;
    }

    public static void uploadReceipt(Context context, List<String> images, ICallBackListener<List<UploadImageBean>> iResultListener) {
        int imageSize=images.size();
        List<String> compressImages=new ArrayList<>();

        ImageUtil.compressImage(context, images, new OnCompressListener() {
            @Override
            public void onStart() {
            }
            @Override
            public void onSuccess(File file) {

                compressImages .add(file.getAbsolutePath());
                if (compressImages.size()>=imageSize){
                    upload(context,TenXunConstans.COS_PATH_RECEIPT,compressImages,iResultListener);
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast("压缩图片失败，请重试");
            }
        });



    }


    // todo 上传回执图片
    public static void upload(Context context, String path, List<String> images, ICallBackListener<List<UploadImageBean>> iResultListener) {
        List<UploadImageBean> iamgesResult = new ArrayList<>();
        if (images != null && !images.isEmpty()) {
            for (String iamgePath : images) {
                upload(context, path, iamgePath, (result, errorMsg) -> {
                    if (!TextUtils.isEmpty(errorMsg)) {
                        iResultListener.onResult(null,errorMsg);
                        return;
                    }
                    iamgesResult.add(result);
                    if (iamgesResult.size() == images.size()) {
                        iResultListener.onResult(iamgesResult,null);
                    }
                });
            }
        }
    }

    public static void upload(Context context, String path, String localImgPath, ICallBackListener<UploadImageBean> iResultListener) {
        // 初始化 TransferConfig，这里使用默认配置，如果需要定制，请参考 SDK 接口文档
        TransferConfig transferConfig = new TransferConfig.Builder().build();
        String cosPath = BuildConfig.image_file_path+path +System.currentTimeMillis() + ".png";
        getKey(context, cosPath, new IResultListener<CosXmlSimpleService>() {
            @Override
            public void onResult(CosXmlSimpleService result) {
                if (result != null) {
                    // 初始化 TransferManager
                    TransferManager transferManager = new TransferManager(result,
                            transferConfig);
                    // 存储桶名称，由 bucketname-appid 组成，appid 必须填入，可以在 COS 控制台查看存储桶名称。
                    String bucket = TenXunConstans.BUCKET;

                    //若存在初始化分块上传的 UploadId，则赋值对应的 uploadId 值用于续传；否则，赋值 null
                    String uploadId = null;

                    // 上传文件
                    COSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosPath,
                            localImgPath, uploadId);
                    //设置返回结果回调
                    cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
                        @Override
                        public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                            if (iResultListener != null) {
                                UploadImageBean uploadImageBean = new UploadImageBean();
                                uploadImageBean.setLocalImage(localImgPath);
                                uploadImageBean.setUploadImage(cosPath);
                                iResultListener.onResult(uploadImageBean,null);
                            }
                        }

                        // 如果您使用 kotlin 语言来调用，请注意回调方法中的异常是可空的，否则不会回调 onFail 方法，即：
                        // clientException 的类型为 CosXmlClientException?，serviceException 的类型为 CosXmlServiceException?
                        @Override
                        public void onFail(CosXmlRequest request,
                                           @Nullable CosXmlClientException clientException,
                                           @Nullable CosXmlServiceException serviceException) {
                            String errorMsg=null;
                            if (clientException!=null){
                                errorMsg=clientException.getMessage();
                            }
                            if (serviceException!=null){
                                errorMsg=serviceException.getMessage();
                            }
                            if (iResultListener != null) {
                                iResultListener.onResult(null,errorMsg);
                            }
                        }
                    });
                }
            }
        });

    }
}
